package com.carl.guli.controller;


import com.carl.guli.common.constant.Constant;
import com.carl.guli.model.AccountInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.SimpleFormController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class BaseController extends SimpleFormController {

    protected Logger logger;

    /**
     * 向客户端返回指定json字符串
     *
     * @param json     json字符串
     * @param response
     */
    protected void printJson(String json, HttpServletResponse response) {
        if (response == null) {
            return;
        }

        try {
            response.setContentType("text/html;charset=UTF-8");
            if (json == null) {
                response.getWriter().write("{}");
            } else {
                response.getWriter().write(json);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向客户端返回成功或失败消息的json字符串，如果参数success为true，返回成功消息，否则返回失败消息
     *
     * @param success  成功或失败
     * @param msg      返回页面的提示信息
     * @param response
     */
    protected void printSuccess(boolean success, String msg, HttpServletResponse response) {
        if (response == null) {
            return;
        }

        try {
            response.setContentType("text/html;charset=UTF-8");

            if (msg == null || msg.trim().length() == 0) {
                response.getWriter().write("{\"success\" : " + success + "}");
            } else {
                response.getWriter().write("{\"success\" : " + success + ", \"msg\" : \"" + msg + "\"}");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向客户端返回成功或失败消息的json字符串，如果参数success为true，返回成功消息，否则返回失败消息
     *
     * @param success  成功或失败
     * @param response
     */
    protected void printSuccess(boolean success, HttpServletResponse response) {
        this.printSuccess(success, null, response);
    }

//	/**
//	 * 生成分页本地线程
//	 *
//	 * @param currPage 当前页码
//	 *
//	 * @param pageSize 页面大小
//	 */
//	protected PageContext createPage(int currPage,int pageSize){
//		PageContext page = PageContext.createPage();
//		page.setCurrentPage(currPage);
//		page.setPageSize(pageSize);
//		return page;
//	}

    /**
     * 用于移动客户端客户端返回json
     *
     * @param success
     * @param resMsg
     * @param json
     * @return
     */
    protected String printJsonM(Integer success, String resMsg, String json) {
        if (json == null) {
            return "{\"resultCode\" : \"" + success.toString() + "\", \"resultMsg\" : \"" + resMsg + "\"}";
        } else {
            return "{\"resultCode\" : \"" + success.toString() + "\", \"resultMsg\" : \"" + resMsg + "\" ," + json + "}";
        }
    }

    /**
     * 设置当前登录的用户信息到session中
     *
     * @param session   当前会话
     * @param accountInfo 当前登录的用户信息
     */
    public static void setSessionAccount(HttpSession session, AccountInfo accountInfo) {
        if (session == null) {
            return;
        }
        session.setAttribute(Constant.CACHE_ACCOUNT, accountInfo);
    }

    protected static AccountInfo getSessionAccount(HttpSession session) {
        if (session == null) {
            return null;
        }

        if (session.getAttribute(Constant.CACHE_ACCOUNT) == null) {
            return null;
        }
        return (AccountInfo) session.getAttribute(Constant.CACHE_ACCOUNT);
    }


//	/**
//	 * 统一异常处理 \n
//     * 向前端返回Json数据
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("/error")
//	@ResponseBody
//	public Result printException(HttpServletRequest request) {
//		Result result = (Result) request.getAttribute("result");
//
//		return result;
//	}

    /**
     * 日志测试方法运行时间
     *
     * @param text
     * @param bt
     * @param et
     */
    protected void logger(String text, Long bt, Long et) {
        if (null == et) {
            logger.info("进入 " + text + " " + new Date(bt));
        } else {
            logger.info("退出 " + text + " 所需要时间为 " + (et - bt) + " 毫秒");
        }
    }

    protected Cookie getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        } else {
            return null;
        }
    }

    /**
     * 将cookie封装到Map里面
     *
     * @param request
     * @return
     */
    private Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    public void createPageHelper(HttpServletRequest request) {
        String currentPage = request.getParameter("currentPage");
        if (currentPage == null) {
            currentPage = "1";
        }
        PageHelper.startPage(Integer.valueOf(currentPage), 20);
    }

    @InitBinder
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) throws Exception {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
        binder.registerCustomEditor(Date.class, dateEditor);
        super.initBinder(request, binder);
    }


}

